<template>
  <div class="preview-print-spread-sheet">
    <el-header
      class="step-header"
      style="overflow: hidden; height: 72px; background: white; border-bottom: 1px solid #ebeef5"
    >
      <el-row type="flex" justify="space-between" align="middle" style="height: 100%">
        <div class="title" style="display: flex; width: 200px; height: 40px; line-height: 40px">
          <i class="header-logo logo online-icon icon-orange-icon" style="font-size: 40px" />
          <span style="font-size: 22px; color: #333; font-weight: bold">打印预览</span>
        </div>
        <el-row class="operation" justify="end">
          <el-button size="default" :icon="Download" @click="doDownload" style="width: 85px"
            >Word</el-button
          >
          <el-button size="default" @click="onCancelClick" style="width: 85px">退出</el-button>
        </el-row>
      </el-row>
    </el-header>
    <el-main style="padding: 16px; background: #f6f6f6">
      <div style="height: calc(100vh - 72px - 16px - 16px)">
        <DocumentEditor
          id="docEditor"
          v-if="isReady"
          :documentServerUrl="documentServerUrl"
          :config="config"
          :events_onDocumentReady="onDocumentReady"
          :events_onError="onError"
          :onLoadComponentError="onLoadComponentError"
        />
      </div>
    </el-main>
  </div>
</template>

<script setup lang="ts">
import { Download } from '@element-plus/icons-vue';
import { DocumentEditor, IConfig } from '@onlyoffice/document-editor-vue';
import { useDownload } from '@/common/hooks/useDownload';
import { useUrlBuilder } from '@/common/hooks/useUrl';
import { generateRandomString, getToken } from '@/common/utils';
import { generateJWT } from '@/common/utils/jwt';
import { IPrintViewProps } from '@/common/types/printView';
import { useOnlyOffice } from './useOnlyOffice';

const props = defineProps<IPrintViewProps>();

const { downloadFile } = useDownload();
const { buildGetUrl } = useUrlBuilder();

const word = { url: '', name: '' };
const {
  isReady,
  printParamList,
  onCloseThirdDialog,
  documentServerUrl,
  onDocumentReady,
  onError,
  onLoadComponentError,
} = useOnlyOffice(props);

const config = ref<IConfig>({
  document: {
    fileType: 'docx',
    key: generateRandomString(10),
    permissions: {
      chat: false,
      comment: false,
      copy: false,
      download: false,
      edit: false,
      fillForms: false,
      modifyContentControl: false,
      modifyFilter: false,
      print: true,
      review: false,
      reviewGroups: undefined,
      commentGroups: null,
      userInfoGroups: undefined,
      protect: false,
    },
    title: '',
    url: '',
  },
  documentType: 'word',
  height: '100%',
  token: '',
  type: 'embedded', // embedded,desktop
  width: '100%',
  editorConfig: {
    lang: 'zh',
    mode: 'view',
    customization: {
      features: {
        print: true,
      },
      close: {
        visible: true,
        text: 'Close',
      },
      logo: {
        visible: false,
      },
      pointerMode: 'select',
      slidePlayerBackground: 'rgba(255, 255, 255, 0.5)',
      toolbarHideFileName: true,
      toolbarNoTabs: false,
    },
    embedded: {
      toolbarDocked: 'top',
    },
  },
});

const doDownload = () => {
  if (!word.url) {
    console.warn('url is empty');
    return;
  }
  downloadFile(word.url, word.name);
};

const onCancelClick = () => {
  if (props.dialog) {
    props.dialog.cancel();
  } else {
    onCloseThirdDialog(true);
  }
};

const initFormData = async (printId: string | undefined) => {
  if (!printId) {
    isReady.value = true;
    return;
  }

  const url = buildGetUrl('admin/report/reportPrint/previewWithUrl', {
    printId: props.printId,
    printParam: encodeURIComponent(JSON.stringify(printParamList.value)),
    renderType: 4,
    Authorization: getToken(),
  });

  word.url = url;
  word.name = props.printName + '.docx';

  console.log('word', word);

  config.value.document!.title = word.name;
  config.value.document!.url = word.url;
  // console.log('config', config.value);
  const token = await generateJWT(
    JSON.parse(JSON.stringify(config.value)),
    process.env.VUE_APP_ONLYOFFICE_JWT_SECRET,
  );
  // console.log('token', token);
  config.value.token = token;

  isReady.value = true;
};

onMounted(() => {
  initFormData(props.printId);
});
</script>

<style scoped>
.preview-print-spread-sheet {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 100;
  width: 100vw;
  height: 100vh;
  background: #f9f9f9;
}
</style>
